package com.baosight.risk.service.rire.impl;

import com.baosight.risk.api.fltd.FlaaNodeAuthoService;
import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.workflow.AfterHandler;
import com.baosight.risk.api.workflow.BeforeHandler;
import com.baosight.risk.api.workflow.UpdateHandler;
import com.baosight.risk.api.xtdc.XtdcAttachService;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.fltd.FlaaNodeAuthoMapper;
import com.baosight.risk.mapper.fltd.FltdTaskMapper;
import com.baosight.risk.mapper.riim.RiimRiskImportMapper;
import com.baosight.risk.mapper.rire.RireRiskEventMapper;
import com.baosight.risk.mapper.rire.RireRiskTargetMapper;
import com.baosight.risk.mapper.rire.RireRiskWarningStatusMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringRuleMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringStatusMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringTargetMapper;
import com.baosight.risk.mapper.xtzy.XtzyUserMapper;
import com.baosight.risk.service.fltd.entity.FltdTask;
import com.baosight.risk.service.fltd.vo.FltdTaskVO;
import com.baosight.risk.service.fltd.vo.NodeTransitionVO;
import com.baosight.risk.service.riim.entity.RiimRiskImport;
import com.baosight.risk.service.riim.vo.RiimRiskImportVO;
import com.baosight.risk.service.rire.entity.RireRiskEvent;
import com.baosight.risk.service.rire.entity.RireRiskTarget;
import com.baosight.risk.service.rire.entity.RireRiskWarningStatus;
import com.baosight.risk.service.rire.vo.RiskWarningStatusVO;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaring;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaringRule;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaringStatus;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaringTarget;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;

@Service("rireRiskReportSubServiceImpl")
@Slf4j
public class RireRiskReportSubServiceImpl extends BaseServiceImpl<RiimRiskImport> implements UpdateHandler, AfterHandler, BeforeHandler {

    @Autowired
    private RireRiskWarningStatusMapper rireRiskWarningStatusMapper;

    @Autowired
    private RiimRiskImportMapper riskImportMapper;

    @Autowired
    private XtzyUserMapper xtzyUserMapper;

    @Autowired
    private FltdProcessService fltdProcessService;

    @Autowired
    private RireRiskTargetMapper rireRiskTargetMapper;

    @Autowired
    private FltdTaskMapper fltdTaskMapper;

    @Autowired
    private RireRiskEventMapper rireRiskEventMapper;

    @Autowired
    private RiwaRiskWaringMapper riwaRiskWaringMapper;

    @Autowired
    private RiwaRiskWaringStatusMapper riwaRiskWaringStatusMapper;

    @Autowired
    private RiwaRiskWaringRuleMapper riwaRiskWaringRuleMapper;

    @Autowired
    private RiwaRiskWaringTargetMapper riwaRiskWaringTargetMapper;

    @Autowired
    private FlaaNodeAuthoMapper flaaNodeAuthoMapper;
    @Autowired
    private FlaaNodeAuthoService flaaNodeAuthoService;


    /**
     * status	当前节点状态
     * nextStatus	下一节点状态
     * nextStatusName	下一节点状态名称
     * acctYear	当前年度
     * quarterCurrent	当前季度
     * deptCode	填报人的部门编码
     * bizGuid 业务id
     * taskGuid 项目id(重点风险id)
     * context 审批意见
     * submitType 提交、回退、结束, 值：(submit, reject, end)
     */
    @Override
    public boolean doAfter(Map<String, Object> params) {
        try {
            //根据biz_guid 查询重点风险披露报告表（T_RIRE_RISK_WARNING_STATUS）获取管理单位、年度、季度
            RiskWarningStatusVO statusVO = rireRiskWarningStatusMapper.getWarningById(params.get("bizGuid").toString());
            if ("B09".equals(statusVO.getStatus())) {
                //根据管理单位、年度、季度、父节点（parentId 不为空）获取重点风险表（T_RIIM_RISK_IMPORT）
                RiimRiskImportVO paramImport = new RiimRiskImportVO();
                paramImport.setAcctYear(statusVO.getAcctYear());
                paramImport.setManageCompCode(statusVO.getManageCompCode());
                List<RiimRiskImport> importList = riskImportMapper.selectManages(paramImport);
                if (importList.size() > 0) {
                    for (RiimRiskImport item : importList) {
                        RireRiskWarningStatus subParam = new RireRiskWarningStatus();
                        subParam.setImportGuid(item.getId());
                        subParam.setAcctYear(statusVO.getAcctYear());
                        subParam.setQuarterCode(statusVO.getQuarterCode());
                        RireRiskWarningStatus subReport=rireRiskWarningStatusMapper.selectOne(subParam);
                        if(!ObjectUtils.isEmpty(subReport)){
                            RiimRiskImport riskImport = new RiimRiskImport();
                            riskImport.setId(item.getParentId());
                            //根据parentId获取上级点位的重点风险
                            RiimRiskImport parentRiskImport = riskImportMapper.selectById(riskImport);
                            //根据重点风险ID、年度、季度，获取上级单位的监控报告
                            RireRiskWarningStatus statusParam = new RireRiskWarningStatus();
                            statusParam.setImportGuid(parentRiskImport.getId());
                            statusParam.setAcctYear(statusVO.getAcctYear());
                            statusParam.setQuarterCode(statusVO.getQuarterCode());
                            List<RiskWarningStatusVO> parentReport = rireRiskWarningStatusMapper.selectList(statusParam, null);
                            for (RiskWarningStatusVO warningStatusVO : parentReport) {
                                //如果上级单位监控报告的当前节点为待填报，则执行数据复制、调用上级单位工作流；如果上级单的当前节点已经汇总（B05\ B07\ B08\ B09）不复制数据，
                                //不调用上级单位工作流；如果上级单位的当前节点为其他，则提示“宝钢股份重点风险监控报告的工作流节点不符合条件，请先提交宝钢股份相同重点风险监控报告的工作流”
                                if ("A01".equals(warningStatusVO.getStatus())) {
                                    if (StringUtils.isNotEmpty(parentRiskImport.getDutyUserCode())) {
                                        XtzyUser xtzyUser = xtzyUserMapper.selectByName(parentRiskImport.getDutyUserCode());
                                        this.copyData(warningStatusVO, statusVO);
                                        this.submit(parentRiskImport, warningStatusVO);
                                    }

                                } else if ("B05".equals(warningStatusVO.getStatus()) || "B07".equals(warningStatusVO.getStatus()) || "B08".equals(warningStatusVO.getStatus()) || "B09".equals(warningStatusVO.getStatus())) {
                                    throw new Exception("宝钢股份重点风险监控报告的工作流节点不符合条件，请先提交宝钢股份相同重点风险监控报告的工作流！");
                                }
                            }
                        }
                    }

                }
            }

        } catch (Exception e) {
            log.error("扭转流程异常：" + e.getMessage());
            return false;
        }

        return true;
    }

    private void submit(RiimRiskImport parentRiskImport, RiskWarningStatusVO statusVO) {
        if (StringUtils.isNotEmpty(parentRiskImport.getDutyUserCode())) {
            XtzyUser xtzyUser = xtzyUserMapper.selectByName(parentRiskImport.getDutyUserCode());
            FltdTaskVO paramTask = new FltdTaskVO();
            paramTask.setFlowNo("fengxianpilubaogao");
            paramTask.setBizGuid(statusVO.getId());
            paramTask.setNodeCode(statusVO.getStatus());
            paramTask.setStatus("open");
            List<FltdTask> taskList = fltdTaskMapper.selectTaskList(paramTask);
            if (taskList.size() > 0) {
                FltdTaskVO taskVoParam = new FltdTaskVO();
                BeanUtils.copyBeanProp(taskVoParam, taskList.get(0));
                try {
                    FltdTask updateTask = new FltdTask();
                    updateTask.setTodoGuid(taskVoParam.getTodoGuid());
                    //走绿色通道
                    updateTask.setGreenFlag("G");
                    fltdTaskMapper.updateByPrimaryKeySelective(updateTask);
                    taskVoParam.setGreenFlag("G");

                    //获取下一节点审批人
                    Map<String, Object> resultMap = flaaNodeAuthoService.getNextUser(taskVoParam, xtzyUser);
                    List<XtzyUser> authUsers = (List<XtzyUser>) resultMap.get("authUsers");
                    if (CollectionUtils.isNotEmpty(authUsers)) {
                        taskVoParam.setCustomUsers(authUsers);

                        //查询指定节点的下一个节点及转移路线
                        String processDefId = fltdProcessService.getProcessDefId(taskVoParam.getProcGuid());
                        NodeTransitionVO nextTransition = flaaNodeAuthoMapper.nextOneNodeTransition(processDefId, "submit-G-1");
                        taskVoParam.setSubmitButton(nextTransition);

                        fltdProcessService.doSubmit(xtzyUser, taskVoParam);
                    }

                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage());
                }
            }
        }
    }

    @Override
    public boolean updateStatus(Map<String, Object> params) {
        return false;
    }

    private void copyData(RiskWarningStatusVO parentVo, RiskWarningStatusVO subVO) {
        //修改监控报告（T_RIRE_RISK_WARNING_STATUS）
        RireRiskWarningStatus updateParam = new RireRiskWarningStatus();
        updateParam.setId(parentVo.getId());
        RireRiskWarningStatus updateEntity = rireRiskWarningStatusMapper.selectOne(updateParam);
        updateEntity.setWarningAccording(subVO.getWarningAccording());
        updateEntity.setNextWaringStatus(subVO.getNextWaringStatus());
        updateEntity.setStrategy(subVO.getStrategy());
        updateEntity.setWaringStatus(subVO.getWaringStatus());
        rireRiskWarningStatusMapper.updateByPrimaryKey(updateEntity);
        //删除上级单位股份的风险指标
        rireRiskTargetMapper.deleteByImportId(parentVo.getId());
        // 复制风险指标（T_RIRE_RISK_TARGET）
        List<RireRiskTarget> sourceImportData = rireRiskTargetMapper.getTargetByImportId(subVO.getId());
        for (RireRiskTarget item : sourceImportData) {
            RireRiskTarget targetRisk = new RireRiskTarget();
            BeanUtils.copyBeanProp(targetRisk, item);
            BeanUtils.initBean(targetRisk);
            targetRisk.setManageCompCode(parentVo.getManageCompCode());
            targetRisk.setManageCompName(parentVo.getManageCompName());
            targetRisk.setImportReportGuid(parentVo.getId());
            targetRisk.setImportGuid(parentVo.getImportGuid());
            rireRiskTargetMapper.insert(targetRisk);
        }
        //删除上级单位股份的风险事件
        rireRiskEventMapper.deleteByImportId(parentVo.getId());
        // 复制风险事件（T_RIRE_RISK_EVENT）
        List<RireRiskEvent> riskEventList = rireRiskEventMapper.getEventByImportId(subVO.getId());
        for (RireRiskEvent item : riskEventList) {
            RireRiskEvent riskEvent = new RireRiskEvent();
            BeanUtils.copyBeanProp(riskEvent, item);
            BeanUtils.initBean(riskEvent);
            riskEvent.setManageCompCode(parentVo.getManageCompCode());
            riskEvent.setManageCompName(parentVo.getManageCompName());
            riskEvent.setImportGuid(parentVo.getImportGuid());
            riskEvent.setImportReportGuid(parentVo.getId());
            rireRiskEventMapper.insert(riskEvent);
        }
        //删除上级单位股份的预警模型
        riwaRiskWaringMapper.deleteByImportId(parentVo.getId());
        // 复制预警模型（T_RIWA_RISK_WARING）
        List<RiwaRiskWaring> riwaRiskWaringList = riwaRiskWaringMapper.getWaringByImportId(subVO.getId());

        List<RiwaRiskWaring> parentWaringList = riwaRiskWaringMapper.getWaringByImportId(parentVo.getId());
        for (RiwaRiskWaring parentWaring : parentWaringList) {
            //删除预警模型-预警状态
            riwaRiskWaringStatusMapper.deleteByWaringId(parentWaring.getId());
            //删除重点风险预警模型-预警规则
            riwaRiskWaringRuleMapper.deleteByWaringId(parentWaring.getId());
            //删除重点风险预警模型-预警指标
            riwaRiskWaringTargetMapper.deleteByWaringId(parentWaring.getId());
        }
        for (RiwaRiskWaring item : riwaRiskWaringList) {
            RiwaRiskWaring riskWaring = new RiwaRiskWaring();
            BeanUtils.copyBeanProp(riskWaring, item);
            BeanUtils.initBean(riskWaring);
            riskWaring.setManageCompCode(parentVo.getManageCompCode());
            riskWaring.setManageCompName(parentVo.getManageCompName());
            riskWaring.setImportGuid(parentVo.getImportGuid());
            riskWaring.setImportReportGuid(parentVo.getId());
            riwaRiskWaringMapper.insert(riskWaring);
            //复制重点风险预警模型-预警状态T_RIWA_RISK_WARING_STATUS
            List<RiwaRiskWaringStatus> riskWaringStatusList = riwaRiskWaringStatusMapper.getWaringStatusByWaringId(item.getId());
            for (RiwaRiskWaringStatus statusItem : riskWaringStatusList) {
                RiwaRiskWaringStatus riskWaringStatus = new RiwaRiskWaringStatus();
                BeanUtils.copyBeanProp(riskWaringStatus, statusItem);
                BeanUtils.initBean(riskWaringStatus);
                riskWaringStatus.setImportGuid(parentVo.getImportGuid());
                riskWaringStatus.setWarningModelGuid(riskWaring.getId());
                riwaRiskWaringStatusMapper.insert(riskWaringStatus);
                //复制--重点风险预警模型-预警规则（T_RIWA_RISK_WARING_RULE）
                List<RiwaRiskWaringRule> waringRule = riwaRiskWaringRuleMapper.getWaringRuleByStatusId(statusItem.getId());
                for (RiwaRiskWaringRule ruleItem : waringRule) {
                    RiwaRiskWaringRule riskWaringRule = new RiwaRiskWaringRule();
                    BeanUtils.copyBeanProp(riskWaringRule, ruleItem);
                    BeanUtils.initBean(riskWaringRule);
                    riskWaringRule.setImportGuid(parentVo.getImportGuid());
                    riskWaringRule.setWaringStatusGuid(riskWaringStatus.getId());
                    riskWaringRule.setWarningModelGuid(riskWaring.getId());
                    riwaRiskWaringRuleMapper.insert(riskWaringRule);
                    //复制重点风险预警模型-预警指标（T_RIWA_RISK_WARING_TARGET）
                    List<RiwaRiskWaringTarget> waringTargetList = riwaRiskWaringTargetMapper.getWaringTargetByRuleId(ruleItem.getId());
                    for (RiwaRiskWaringTarget targetItem : waringTargetList) {
                        RiwaRiskWaringTarget riskWaringTarget = new RiwaRiskWaringTarget();
                        BeanUtils.copyBeanProp(riskWaringTarget, targetItem);
                        BeanUtils.initBean(riskWaringTarget);
                        riskWaringTarget.setImportGuid(parentVo.getImportGuid());
                        riskWaringTarget.setWarningModelGuid(riskWaring.getId());
                        riskWaringTarget.setWaringStatusGuid(riskWaringStatus.getId());
                        riskWaringTarget.setWarningRuleId(riskWaringRule.getId());
                        riwaRiskWaringTargetMapper.insert(riskWaringTarget);
                    }
                }

            }
        }
    }

    /**
     * status	当前节点状态
     * nextStatus	下一节点状态
     * nextStatusName	下一节点状态名称
     * acctYear	当前年度
     * quarterCurrent	当前季度
     * deptCode	填报人的部门编码
     * bizGuid 业务id
     * bizName 业务名称
     * taskGuid 项目id(重点风险id)
     * context 审批意见
     * submitType 提交、回退、结束, 值：(submit, reject, end)
     */
    @Override
    public boolean doBefore(Map<String, Object> params) {
        return false;
    }
}
